<template>
  <el-dialog :visible.sync="visible" 
  :title="title" 
  :append-to-body="true"
  :lock-scroll="true"
  :close-on-click-modal="false" 
  :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" 
      v-loading="loading" 
      @keydown.enter.native.prevent="dataFormSubmitHandle()">
      <el-row>
        <el-col :span="24">
          <el-form-item size="mini">
            <!-- :check-strictly="true" ->父子不互相关联 -->
            <el-tree
              :data="menuList"
              :props="{ label: 'permsName', children: 'children' }"
              node-key="permId"
              ref="menuListTree"
            
              accordion
              show-checkbox>
            </el-tree>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确认</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import servicesApi from '@/services/servicesApi'
export default {
  data() {
    return {
      visible: false,
      loading: false,
      title: '权限维护',
      menuList: [],
      dataForm: {
        roleId: 1,
        permslist: [4, 5],
      }
    }
  },
  computed: {
    dataRule() {
      return {
        name: [
          { required: true, message: '请输入角色名', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // this.getMenuList()
  },
  methods: {
    init(row) {
      this.visible = true
      this.dataForm.roleId = row.id
      
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.$refs.menuListTree.setCheckedKeys([]) //-清空当前的选择
        Promise.all([
          this.getMenuList(), 
        ]).then(() => {
          this.getPermsSelected()
          this.title = row.name + ' 权限维护'
        })
      })
      
    },
    // 获取菜单列表
    getMenuList() {
      // return 解决异步函数！！！！！！！！！
      this.loading = true
      return servicesApi.getAllPerms().then(res => {
        this.loading = false
        if (res.data.code !== 200) {
          return this.$message.error(res.data.msg)
        }
        this.menuList = res.data.data
      })
    },
    // 获取已有权限
    getPermsSelected() {
      servicesApi.getRolePerms(this.dataForm.roleId).then(res => {
        if (res.data.code !== 200) {
          return this.$message.error(res.data.msg)
        }
        this.dataForm.permslist = res.data.data
        // console.log('已有权限=%s', this.dataForm.permslist)

        // console.log('树形所有权限%o', this.menuList)
        //==========树形数据渲染===========
        // 1. 只设置叶子
        // 问题：但是分支无论是半选还是全选都没有显示
        // this.$refs.menuListTree.setCheckedKeys(this.dataForm.permslist,true)
        //2.函数式编程 setChecked(item, true) 
        // 问题:选中叶子，分支节点不是半选状态而是全选状态，
        // this.dataForm.permslist.forEach(item =>{
        //   this.$refs.menuListTree.setChecked(item, true)
        // })

        // 3、isLeaf
        // 后端返回数据是全选半选一起返回，el-tree严格模式如果勾选父节点子节点会全部勾选。
        // 根据isLeaf 过滤只获取叶子节点(最底层节点)，父节点自然会根据这些节点判断半选全选状态
        const arr = []
        this.dataForm.permslist.forEach(item => {
          let node = this.$refs.menuListTree.getNode(item);
          if (node === null) {
            // console.log('空=%d', item)
            // continue
          } else if (node.isLeaf) { //关键，过滤掉不是叶子节点的
            // // console.log(node.isLeaf)
            arr.push(item)
            // console.log('叶子=%d', item)
          } else if (!node.isLeaf) {
            // console.log('分支=%d', item)
          }
        })
        this.$refs.menuListTree.setCheckedKeys(arr)
        // console.log('权限列表arr=%s', arr)
      })
    },

    // 表单提交
    dataFormSubmitHandle: debounce(function() {
      // let list = this.$refs.menuListTree.getCheckedKeys(true)
      // this.dataForm.permslist = list
      // // console.log(list)
      // this.$message({
      //   message: '操作成功',
      //   type: 'success',
      //   duration: 500,
      //   onClose: () => {
      //     this.visible = false
      //     this.$emit('refreshDataList')
      //   }
      // })

      let permslist = this.$refs.menuListTree.getCheckedKeys() //true:只选叶节点,默认false
      let pnode = this.$refs.menuListTree.getHalfCheckedKeys()
      this.dataForm.permslist = permslist.concat(pnode)

      // this.dataForm.permslist =[
      //   this.$refs.menuListTree.getCheckedKeys(),
      //   this.$refs.menuListTree.getHalfCheckedKeys()
      // ]

      // console.log(this.dataForm.permslist)
      servicesApi.updateRolePerms(this.dataForm).then(res => {
        if (res.data.code === 200) {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        } else {
          this.$message.error(res.data.msg)
        }
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
